package com.innovation.ic.sc.web.controller.sc_data;

import com.alibaba.fastjson.JSON;
import com.innovation.ic.sc.base.model.sc.Client;
import com.innovation.ic.sc.base.pojo.constant.handler.RedisStorage;
import com.innovation.ic.sc.base.pojo.variable.ServiceResult;
import com.innovation.ic.sc.base.pojo.variable.ApiResult;
import com.innovation.ic.sc.web.controller.AbstractController;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

/**
 * @desc   客户端信息API
 * @author linuo
 * @time   2022年8月11日15:29:23
 */
@Api(value = "客户端API", tags = "ClientController")
@RestController
@RequestMapping("/api/v2/initClient")
//@DefaultProperties(defaultFallback = "defaultFallback")
public class InitClientController extends AbstractController {

    private static final Logger log = LoggerFactory.getLogger(InitClientController.class);

    /**
     * 删除redis中CLIENT:开头的数据，将client表中的数据导入redis
     * @return 返回处理结果
     */
    @HystrixCommand
    @RequestMapping(value = "/importClientIntoRedis", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> importClientIntoRedis(HttpServletRequest request, HttpServletResponse response) {
        log.info("删除redis中CLIENT:开头的数据，将client表中的数据导入redis");

        // 删除redis中CLIENT:开头的数据
        Set<String> keySet = serviceHelper.getRedisManager().keysPrefix(RedisStorage.CLIENT);
        serviceHelper.getRedisManager().del(keySet);
        // 将client表中的数据导入redis
        ServiceResult<List<Client>> serviceResult = clientService.findAll();
        if (null != serviceResult && null != serviceResult.getResult()) {
            List<Client> clientList = serviceResult.getResult();
            for (int i = 0; i < clientList.size(); i++) {
                Client client = clientList.get(i);
                serviceHelper.getRedisManager().sAdd(RedisStorage.CLIENT, JSON.toJSONString(client));
            }
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.INSERT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }
}